﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Practices.Prism.Commands;
using WeiboPlus.Common;
using WeiboPlus.Models;
using WeiboPlus.Service;
using WeiboPlus.Converter;
using Coding4Fun.Phone.Controls;
using Microsoft.Xna.Framework.Media;
using System.IO.IsolatedStorage;
using System.Windows.Resources;
using ImageTools.IO;
using ImageTools.IO.Png;
using ImageTools.IO.Gif;
using ImageTools.IO.Jpeg;
using ImageTools;

namespace WeiboPlus.Shell.ViewModel
{
    public class StatusDetailViewModel : SNSStatusViewModel
    {
        #region field

        public bool ShowCommentsToOriginal 
        {
            get
            {
                return HasRetweet && !(Item is Renren.RenrenSNSStatus);
            }
        }

        bool isCommentAlso;

        public bool IsCommentAlso
        {
            get { return isCommentAlso; }
            set
            {
                isCommentAlso = value;
                RaisePropertyChanged("IsCommentAlso");
            }
        }

        public SNSProviderType ServiceProvider
        {
            get { return Item.Provider; }
        }


        private int pagecount = 10;
        private ObservableCollection<SNSStatusViewModel> comments = new ObservableCollection<SNSStatusViewModel>(); private ObservableCollection<SNSStatusViewModel> _ocomments = new ObservableCollection<SNSStatusViewModel>();
        private IStatusService _statusSvc;


        #endregion

        #region Properties

        private int numberOfCharacter;

        public int NumberOfCharacter
        {
            get { return numberOfCharacter; }
            set
            {
                numberOfCharacter = value;
                RaisePropertyChanged("NumberOfCharacter");
            }
        }

        public Action<SNSStatusViewModel> OnRefreshed { get; set; }

        public bool HasExtendedImage
        {
            get { return extendedImage != null; }
        }

        ExtendedImage extendedImage;

        public ExtendedImage ExtendedImage
        {
            get { return extendedImage; }
            set
            {
                extendedImage = value;
                RaisePropertyChanged(() => ExtendedImage);
                RaisePropertyChanged(() => HasExtendedImage);
            }
        }

        public bool HasExtendedReImage
        {
            get { return extendedReImage != null; }
        }

        ExtendedImage extendedReImage;

        public ExtendedImage ExtendedReImage
        {
            get { return extendedReImage; }
            set
            {
                extendedReImage = value;
                RaisePropertyChanged(() => ExtendedReImage);
                RaisePropertyChanged(() => HasExtendedReImage);
            }
        }

        bool loaded = true;

        public bool Loaded
        {
            get { return loaded; }
            set { loaded = value; RaisePropertyChanged(() => Loaded); }
        }

        int pivotSelectedIndex;

        public int PivotSelectedIndex
        {
            get
            {
                return pivotSelectedIndex;
            }
            set
            {
                pivotSelectedIndex = value;
                RaisePropertyChanged(() => PivotSelectedIndex);
                //PerformGetItems();
            }
        }

        string repostText;

        public string RepostText
        {
            get
            {
                return repostText;
            }
            set
            {
                repostText = value;
                RaisePropertyChanged(() => RepostText);
            }
        }

        string replayTextOriginal;

        public string CommentTextToOriginal
        {
            get
            {
                return replayTextOriginal;
            }
            set
            {
                replayTextOriginal = value;
                RaisePropertyChanged("CommentTextToOriginal");
            }
        }

        string replayText;

        public string CommentText
        {
            get
            {
                return replayText;
            }
            set
            {
                replayText = value;
                RaisePropertyChanged(() => CommentText);
            }
        }

        bool HasComments
        {
            get
            {
                return comments.Count > 0;
            }
            set
            {
                RaisePropertyChanged(() => HasComments);
            }
        }

        private SNSStatusViewModel defaultItem;

        public SNSStatusViewModel DefaultItem
        {
            get
            {
                return defaultItem;
            }
            set
            {
                defaultItem = value;
                RaisePropertyChanged(() => DefaultItem);
            }
        }

        public ObservableCollection<SNSStatusViewModel> OriginalComments
        {
            get { return _ocomments; }
            set
            {
                _ocomments = value;
                RaisePropertyChanged(() => OriginalComments);
            }
        }

        public ObservableCollection<SNSStatusViewModel> Comments
        {
            get { return comments; }
            set
            {
                comments = value;
                RaisePropertyChanged(() => Comments);
            }
        }

        public DelegateCommand Repost { get; set; }
        public DelegateCommand Reply { get; set; }
        public DelegateCommand ReplyToOriginal { get; set; }
        public DelegateCommand MoreComments { get; set; }
        public DelegateCommand MoreOriginalComments { get; set; }
        public DelegateCommand RefreshComments { get; set; }
        public DelegateCommand<object> SaveImageCommand { get; set; }
        public DelegateCommand<object> SaveImageAsWallpaperCommand { get; set; }

        #endregion

        #region ctor

        public StatusDetailViewModel(SNSStatus status)
        {
            Decoders.AddDecoder<PngDecoder>();
            Decoders.AddDecoder<GifDecoder>();
            Decoders.AddDecoder<JpegDecoder>();

            Item = status;

            Initialize();

            LoadData();

            GetImages(status);

            Repost = new DelegateCommand(RepostMethod, () => { return !Loading; });
            Reply = new DelegateCommand(ReplyMethod, () => { return !Loading; });
            ReplyToOriginal = new DelegateCommand(ReplyOriginalMethod, () => { return !Loading; });

            MoreComments = new DelegateCommand(MoreCommentsMethod, () => { return !Loading; });
            MoreOriginalComments = new DelegateCommand(MoreCommentsMethod, () => { return !Loading; });
            RefreshComments = new DelegateCommand(RefreshCommentsMethod, () => { return !Loading; });
            if (Item.RetweetedStatus != null)
            {
                RepostText = "//@" + Item.User.AccountName + " " + Item.Text;
                NumberOfCharacter = repostText.Length;
                //CommentText = AppResx.Reply+"@" + Item.User.AccountName + ": ";
            }
            SaveImageCommand = new DelegateCommand<object>(SaveImage);
            SaveImageAsWallpaperCommand = new DelegateCommand<object>(SaveImageAsWallpaper);
        }

        #endregion

        private void SaveImage(object o)
        {
            var type = o as string;
            var image = null as ExtendedImage;

            switch (type)
            {
                case "Image":
                    image = ExtendedImage as ExtendedImage;
                    break;
                case "RetweetImage":
                    image = ExtendedReImage as ExtendedImage;
                    break;
                default:
                    break;
            }

            if (image == null)
            {
                return;
            }

            var name = null as string;

            switch (type)
            {
                case "Image":
                    name = ExtendedImage.UriSource.AbsoluteUri;
                    break;
                case "RetweetImage":
                    name = ExtendedReImage.UriSource.AbsoluteUri;
                    break;
                default:
                    break;
            }

            if (name == null)
            {
                return;
            }

            name = name.Substring(name.LastIndexOf("/") + 1);

            if (name.IndexOf(".") == -1)
            {
                name += ".jpg";
            }

            SaveToCameraRoll(image, name);
        }

        private void SaveImageAsWallpaper(object o)
        {
            SaveImage(o);
        }

        private void SaveToCameraRoll(ExtendedImage image, string name)
        {
            var wb = image.ToBitmap();

            using (var ms = new MemoryStream())
            {
                // Encode the WriteableBitmap object to a JPEG stream.
                wb.SaveJpeg(ms, wb.PixelWidth, wb.PixelHeight, 0, 85);
                ms.Flush();
                ms.Seek(0, 0);

                // Save the image to the camera roll or saved pictures album.
                var library = new MediaLibrary();

                // Save the image to the camera roll album.
                var pic = library.SavePictureToCameraRoll(name, ms);

                var toast = new ToastPrompt
                {
                    Message = AppResx.ImageSaved,
                };
                toast.Show();
            }
        }

        private void SaveToCameraRoll(BitmapSource image, string name)
        {
            var wb = new WriteableBitmap(image);

            using (var ms = new MemoryStream())
            {
                // Encode the WriteableBitmap object to a JPEG stream.
                wb.SaveJpeg(ms, wb.PixelWidth, wb.PixelHeight, 0, 85);
                ms.Flush();
                ms.Seek(0, 0);

                // Save the image to the camera roll or saved pictures album.
                var library = new MediaLibrary();

                // Save the image to the camera roll album.
                var pic = library.SavePictureToCameraRoll(name, ms);

                var toast = new ToastPrompt
                {
                    Message = AppResx.ImageSaved,
                };
                toast.Show();
            }
        }

        protected override void Initialize()
        {
            //base.Initialize();
            _statusSvc = PhoneApplicationController.Current.Container.Resolve<IStatusService>(Item.Provider.ToString());
            _statusSvc.ProviderResolver = () => SNSProviderManager.GetFactory(Item.Account).GetProvider();
            _statusSvc.FactoryResolver = () => SNSProviderManager.CreateFactory(Item.Account);
            _statusSvc.Account = Item.Account;

            InitStatusInfoText();
        }

        private void RepostMethod()
        {
            if (string.IsNullOrEmpty(RepostText))
                return;

            Loading = true;
            var request = new SNSRequest() { Type = SNSType.RepostStatus, WebMethod = Hammock.Web.WebMethod.Post, Status = Item };
            //renren
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.FORWARD_ID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.FORWARD_OWNER, Item.User.Id.ToString()));
            //request.Parameters.Add(new SNSParameter(SNSParametersConstants.STATUS, RepostText));

            //for sina
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.STATUS_TEXT, RepostText));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.IS_COMMENT, "3"));//SINA|是否在转发的同时发表评论。0表示不发表评论，1表示发表评论给当前微博，2表示发表评论给原微博，3是1、2都发表。默认为0。 

            //For tencent
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CONTENT, RepostText));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CLIENT_IP, "127.0.0.1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REID, Item.Id.ToString()));

            ThreadPool.QueueUserWorkItem((o) =>
            {
                _statusSvc.AddComment(o as SNSRequest, (data, result) =>
                {
                    if (!result.IsSuccess)
                    {
                        //{"request":"/statuses/repost.json","error_code":"400","error":"40025:Error: repeated weibo text!"}
                        //{"request":"/statuses/repost.json","error_code":"400","error":"40028:不要太贪心哦！你已经发过一次啦。"}
                        string message = result.Message;
                        if (message.Contains("repeated") || message.Contains("发过一次"))
                        {
                            message = AppResx.StatusrRepeatedText;
                        }
                        //fixed by Kenny 2011-09-01 00:31:00
                        ExecuteOnUIThread(() => { MessageBox.Show(message); Loading = false; });
                        return;
                    }
                    ExecuteOnUIThread(() =>
                    {
                        if (data != null)
                        {
                            //MessageBox.Show(AppResx.RepostSuccessText);
                            var toast = new ToastPrompt
                            {
                                Message = AppResx.RepostSuccessText,
                            };
                            toast.Show();
                        }

                        Loading = false;
                        RepostText = string.Empty;
                    });
                });

            }, request);

        }

        private void ReplyMethod()
        {
            if (string.IsNullOrEmpty(CommentText))
                return;

            Loading = true;
            var request = new SNSRequest() { Type = SNSType.AddComment, WebMethod = Hammock.Web.WebMethod.Post, Status = Item };


            //for renren
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.USER_ID, Item.User.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.SHARE_ID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CALL_ID, Item.Id.ToString()));
            //for sina
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COMMENT, CommentText));
            //request.Parameters.Add(new SNSParameter(SNSParametersConstants.CID, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.WITHOUT_MENTION, "0"));//SINA|1：回复中不自动加入“回复@用户名”，0：回复中自动加入“回复@用户名”.默认为0. 
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COMMENT_ORI, "0"));//SINA|当评论一条转发微博时，是否评论给原微博。0:不评论给原微博。1：评论给原微博。默认0. 


            //For tencent
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CONTENT, CommentText));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CLIENT_IP, "127.0.0.1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REID, Item.Id.ToString()));

            ThreadPool.QueueUserWorkItem((o) =>
          {
              _statusSvc.AddComment(o as SNSRequest, (data, result) =>
              {
                  if (!result.IsSuccess)
                  {
                      ExecuteOnUIThread(() => { MessageBox.Show(result.Message); Loading = false; });
                      return;
                  }
                  if (data != null)
                  {
                      ExecuteOnUIThread(() =>
                      {
                          var viewmodel = new SNSStatusViewModel(data);
                          Comments.Insert(0, viewmodel);
                          Loading = false;
                          CommentText = string.Empty;

                          if (OnRefreshed != null)
                          {
                              ExecuteOnUIThread(() =>
                              {
                                  OnRefreshed(viewmodel);
                              });
                          }
                      });
                  }
              });
          }, request);
        }

        private void ReplyOriginalMethod()
        {
            if (string.IsNullOrEmpty(CommentTextToOriginal))
                return;

            Loading = true;
            var request = new SNSRequest() { Type = SNSType.AddComment, WebMethod = Hammock.Web.WebMethod.Post, Status = Item };


            //for renren
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.USER_ID, Item.RetweetedStatus.User.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.SHARE_ID, Item.RetweetedStatus.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CALL_ID, Item.RetweetedStatus.Id.ToString()));
            //for sina
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.RetweetedStatus.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COMMENT, CommentTextToOriginal));
            //request.Parameters.Add(new SNSParameter(SNSParametersConstants.CID, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.WITHOUT_MENTION, "0"));//SINA|1：回复中不自动加入“回复@用户名”，0：回复中自动加入“回复@用户名”.默认为0. 
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COMMENT_ORI, "0"));//SINA|当评论一条转发微博时，是否评论给原微博。0:不评论给原微博。1：评论给原微博。默认0. 


            //For tencent
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CONTENT, CommentTextToOriginal));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CLIENT_IP, "127.0.0.1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REID, Item.RetweetedStatus.Id.ToString()));

            ThreadPool.QueueUserWorkItem((o) =>
            {
                _statusSvc.AddComment(o as SNSRequest, (data, result) =>
                {
                    if (!result.IsSuccess)
                    {
                        ExecuteOnUIThread(() => { MessageBox.Show(result.Message); Loading = false; });
                        return;
                    }
                    if (data != null)
                    {
                        ExecuteOnUIThread(() =>
                        {
                            var viewmodel = new SNSStatusViewModel(data);
                            this.OriginalComments.Insert(0, viewmodel);
                            Loading = false;
                            CommentTextToOriginal = string.Empty;

                            if (OnRefreshed != null)
                            {
                                ExecuteOnUIThread(() =>
                                {
                                    OnRefreshed(viewmodel);
                                });
                            }
                        });
                    }
                });
            }, request);
        }

        private void MoreCommentsMethod()
        {
            SNSRequest request = null;
            string pageflag = "1";
            long pagetime = 0;
            long maxid = 0;

            request = new SNSRequest() { Type = SNSType.CommentsByID };
            GetPagingInfo(Comments, ref pagetime, ref maxid, false);

            //sina
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, pagecount + ""));

            //tencent
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.FLAG, "1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ROOTID, Item.Id.ToString()));

            if (maxid != 0)
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.MAX_ID, (maxid > 0 ? (maxid - 1) : 0) + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, pageflag));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, pagetime + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.TWITTERID, maxid + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));
            _statusSvc.GetTimeline(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    ExecuteOnUIThread(() => { Loading = false; MessageBox.Show(result.Message); });
                    return;
                }

                PopupComments(Comments, data, false);

                ExecuteOnUIThread(() =>
                {
                    if (OnNextPagePerformed != null)
                    {
                        OnNextPagePerformed();
                    }
                });

            });

            Loading = true;
        }

        private void MoreOriginalCommentsMethod()
        {
            SNSRequest request = null;
            string pageflag = "1";
            long pagetime = 0;
            long maxid = 0;

            request = new SNSRequest() { Type = SNSType.CommentsByID };
            GetPagingInfo(OriginalComments, ref pagetime, ref maxid, false);

            //sina
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.RetweetedStatus.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, pagecount + ""));

            //tencent
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.FLAG, "1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ROOTID, Item.RetweetedStatus.Id.ToString()));

            if (maxid != 0)
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.MAX_ID, (maxid > 0 ? (maxid - 1) : 0) + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, pageflag));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, pagetime + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.TWITTERID, maxid + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));
            _statusSvc.GetTimeline(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    ExecuteOnUIThread(() => { Loading = false; MessageBox.Show(result.Message); });
                    return;
                }

                PopupComments(OriginalComments, data, false);

                ExecuteOnUIThread(() =>
                {
                    if (OnNextPagePerformed != null)
                    {
                        OnNextPagePerformed();
                    }
                });

            });

            Loading = true;
        }

        private void RefreshCommentsMethod()
        {
            SNSRequest request = null;
            string pageflag = "2";
            long pagetime = 0;
            long sinceid = 0;

            request = new SNSRequest() { Type = SNSType.CommentsByID };
            GetPagingInfo(Comments, ref pagetime, ref sinceid, true);

            //sina
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.Id.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, pagecount + ""));

            //tencent
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.FLAG, "1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.ROOTID, Item.Id.ToString()));

            if (sinceid != 0)
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.SINCE_ID, (sinceid + 1) + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, pageflag));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, pagetime + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.TWITTERID, sinceid + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));

            _statusSvc.GetTimeline(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    ExecuteOnUIThread(() => { Loading = false; });
                    return;
                }

                PopupComments(Comments, data, false);

                if (OnRefreshed != null && data != null && data.Count > 0)
                {
                    ExecuteOnUIThread(() =>
                    {
                        OnRefreshed(Comments[0]);
                    });
                }
            });

            Loading = true;
        }

        private void GetImages(SNSStatus status)
        {
            if (!string.IsNullOrEmpty(Item.BmiddlePic))
            {
                var image = new ImageTools.ExtendedImage();

                var uri = new Uri(status.BmiddlePic, UriKind.Absolute);

                image.UriSource = uri;

                ExtendedImage = image;
            }
            else if (!string.IsNullOrEmpty(Item.ThumbnailPic))
            {
                var image = new ImageTools.ExtendedImage();

                var uri = new Uri(status.ThumbnailPic, UriKind.Absolute);

                image.UriSource = uri;

                ExtendedImage = image;
            }

            if (Item.RetweetedStatus != null && !string.IsNullOrEmpty(Item.RetweetedStatus.BmiddlePic))
            {
                var image = new ImageTools.ExtendedImage();

                var uri = new Uri(Item.RetweetedStatus.BmiddlePic, UriKind.Absolute);

                image.UriSource = uri;

                ExtendedReImage = image;

                //RetweetImage = new Uri(Item.RetweetedStatus.BmiddlePic, UriKind.Absolute);
            }
            else if (Item.RetweetedStatus != null && !string.IsNullOrEmpty(Item.RetweetedStatus.ThumbnailPic))
            {
                var image = new ImageTools.ExtendedImage();

                var uri = new Uri(Item.RetweetedStatus.ThumbnailPic, UriKind.Absolute);

                image.UriSource = uri;

                ExtendedReImage = image;

                //RetweetImage = new Uri(Item.RetweetedStatus.ThumbnailPic, UriKind.Absolute);
            }

            if (Item.User != null && !string.IsNullOrEmpty(Item.User.ProfileImageUrl))
            {
                FaceImageUri = new Uri(Item.User.ProfileImageUrl, UriKind.Absolute);
            }
        }

        protected override void LoadData()
        {
            if (Item.User == null)
                return;
            //if (Item.Provider == SNSProviderType.RenRen)
            //{
            //    if (Item.CommentCount > 0 && Item.Comments != null)
            //    {
            //        PopupComments(Comments, Item.Comments, false);
            //    }
            //    //return;
            //}
            //base.LoadData();
            var request = new SNSRequest() { Type = SNSType.CommentsByID };

            //renren
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.USER_ID, Item.User.Id.ToString()));
            var renrenS = Item as WeiboPlus.Renren.RenrenSNSStatus;
            if (renrenS != null)
            {
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.FEED_TYPE, renrenS.FeedType.ToString()));
                if (renrenS.RetweetedStatus != null)
                    request.Parameters.Add(new SNSParameter(SNSParametersConstants.ROOTID, renrenS.SourceId.ToString()));
                else
                    request.Parameters.Add(new SNSParameter(SNSParametersConstants.ROOTID, Item.Id.ToString()));
            }
            else
            {
                //sina
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.Id.ToString()));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, 10 + ""));

                //tencent
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.FLAG, "1"));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.ROOTID, Item.Id.ToString()));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, "0"));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, "0"));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, 10 + ""));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.TWITTERID, "0"));
            }



            _statusSvc.GetTimeline(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    //ExecuteOnUIThread(() => {MessageBox.Show(result.Message); Loading = false;});
                    //no comment;
                    return;
                }
                PopupComments(Comments, data, false);
                ExecuteOnUIThread(() =>
                {
                    if (OnNextPagePerformed != null)
                    {
                        OnNextPagePerformed();
                    }
                });
            });

            if (HasRetweet && !(Item is Renren.RenrenSNSStatus))
            {
                request = new SNSRequest() { Type = SNSType.CommentsByID };
                //renren
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.USER_ID, Item.RetweetedStatus.User.Id.ToString()));

                //sina
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.ID, Item.RetweetedStatus.Id.ToString()));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, 10 + ""));

                //tencent
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.FLAG, "1"));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.ROOTID, Item.RetweetedStatus.Id.ToString()));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, "0"));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, "0"));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, 10 + ""));
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.TWITTERID, "0"));

                _statusSvc.GetTimeline(request, (data, result) =>
                {
                    if (!result.IsSuccess)
                    {
                        //ExecuteOnUIThread(() => {MessageBox.Show(result.Message); Loading = false;});
                        //no comment;
                        return;
                    }

                    PopupComments(OriginalComments, data, false);
                    ExecuteOnUIThread(() =>
                    {
                        if (OnNextPagePerformed != null)
                        {
                            OnNextPagePerformed();
                        }
                    });
                });
            }
        }

        private void PopupComments(ObservableCollection<SNSStatusViewModel> items, IList<SNSStatus> data, bool isInsert)
        {
            if (data != null && data.Count > 0)
            {
                foreach (var status in data)
                {
                    var viewmodel = new SNSStatusViewModel(status);
                    if (isInsert)
                    {
                        ExecuteOnUIThread(() =>
                        {
                            items.Insert(0, viewmodel);
                        });
                    }
                    else
                    {
                        ExecuteOnUIThread(() =>
                        {
                            items.Add(viewmodel);
                        });

                        //Items.Add(new SNSStatusViewModel(status_copy));
                    }
                    Thread.Sleep(100);
                }
            }
            Thread.Sleep(600);
            ExecuteOnUIThread(() =>
            {
                Loading = false;
                HasComments = HasComments;
                //if (OnRefreshed != null && data.Count > 0)
                //{
                //    OnRefreshed(items[0]);
                //}
            });
        }

        private static void GetPagingInfo(IEnumerable<SNSStatusViewModel> items, ref long pagetime, ref long id, bool isRefresh)
        {
            if (isRefresh)
            {
                var firstItemTencent = items.FirstOrDefault(item => item.Item.Account.ServiceProvider == SNSProviderType.Tencent);
                if (firstItemTencent != null)
                {
                    pagetime = firstItemTencent.Item.Timestamp;
                }

                //for sina

                var firstItem = items.FirstOrDefault();
                if (firstItem != null)
                {
                    id = firstItem.Item.Id;
                }
            }
            else
            {
                var firstItemTencent = items.LastOrDefault(item => item.Item.Account.ServiceProvider == SNSProviderType.Tencent);
                if (firstItemTencent != null)
                {
                    pagetime = firstItemTencent.Item.Timestamp;
                }

                //for sina

                var firstItem = items.LastOrDefault();
                if (firstItem != null)
                {
                    id = firstItem.Item.Id;
                }
            }
        }

        public Action OnNextPagePerformed { get; set; }
    }
}
